<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.orderNumber" placeholder="订单编号" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.orderProgress" placeholder="订单进度" clearable style="width: 150px;" class="filter-item">
        <el-option v-for="item in progressList" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-input v-model="tempOrderProduct" placeholder="暂未选择商品" disabled class="product-choose-input">
        <el-button slot="append" v-waves @click="handleProductChoose">
          选择商品
        </el-button>
      </el-input>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        筛选
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      max-height="690"
      highlight-current-row
      style="width: 100%;"
      :row-style="{height:'32px'}"
      :default-sort="{prop: 'orderId', order: null}"
      tooltip-effect="light"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="订单编号" align="center" fixed prop="orderId" sortable="custom" width="190px">
        <template slot-scope="{row}">
          <span>{{ row.orderNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下单用户" align="center" prop="userId" sortable="custom" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span>{{ row.realName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货人姓名" align="center" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span>{{ row.deliveryName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品信息" align="center" width="110px">
        <template slot-scope="{row}">
          <el-popover placement="bottom" width="550" trigger="click" title="商品信息">
            <div>
              <el-row :gutter="20">
                <el-col :span="4" style="text-align: right"><p style="font-weight: bolder">商品编号</p></el-col>
                <el-col :span="8"><p style="color: #959494">{{ row.productId }}</p></el-col>
                <el-col :span="4" style="text-align: right"><p style="font-weight: bolder">商品名</p></el-col>
                <el-col :span="8"><p style="color: #959494">{{ row.productName }}</p></el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="4" style="text-align: right"><p style="font-weight: bolder">规格编号</p></el-col>
                <el-col :span="8"><p style="color: #959494">{{ row.itemId }}</p></el-col>
                <el-col :span="4" style="text-align: right"><p style="font-weight: bolder">规格名</p></el-col>
                <el-col :span="8"><p style="color: #959494">{{ row.itemName }}</p></el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="4" style="text-align: right"><p style="font-weight: bolder">商品图片</p></el-col>
                <el-col :span="8"><p><el-image :key="row.orderId" style="max-width: 32px; max-height: 24px" :src="row.productImg" :preview-src-list="[ row.productImg ]" /></p></el-col>
                <el-col :span="4" style="text-align: right"><p style="font-weight: bolder">属性详情</p></el-col>
                <el-col :span="8"><p style="color: #959494">{{ row.itemAttrs }}</p></el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="4" style="text-align: right"><p style="font-weight: bolder">单价</p></el-col>
                <el-col :span="8"><p style="color: #959494">￥{{ roundPrice(row.price) }}</p></el-col>
                <el-col :span="4" style="text-align: right"><p style="font-weight: bolder">购买数量</p></el-col>
                <el-col :span="8"><p style="color: #959494">{{ row.number }}</p></el-col>
              </el-row>
            </div>
            <el-button slot="reference" size="mini">查看</el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="其他信息" align="center" width="110px">
        <template slot-scope="{row}">
          <el-popover placement="bottom" width="400" trigger="click">
            <el-divider>收货信息</el-divider>
            <el-row :gutter="20">
              <el-col :span="8" style="text-align: right"><p style="font-weight: bolder">收货姓名</p></el-col>
              <el-col :span="16"><p style="color: #959494">{{ row.deliveryName }}</p></el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8" style="text-align: right"><p style="font-weight: bolder">收货电话</p></el-col>
              <el-col :span="16"><p style="color: #959494">{{ row.deliveryPhone }}</p></el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8" style="text-align: right"><p style="font-weight: bolder">收货地址</p></el-col>
              <el-col :span="16"><p style="color: #959494">{{ row.deliveryProv }} {{ row.deliveryCity }} {{ row.deliveryDist }} {{ row.deliveryAddr }}</p></el-col>
            </el-row>
            <el-divider>备注</el-divider>
            <el-row :gutter="20">
              <el-col :span="8" style="text-align: right"><p style="font-weight: bolder">订单备注</p></el-col>
              <el-col :span="16"><p style="color: #959494">{{ row.orderNote }}</p></el-col>
            </el-row>
            <el-divider>物流信息</el-divider>
            <el-row :gutter="20">
              <el-col :span="8" style="text-align: right"><p style="font-weight: bolder">物流单号</p></el-col>
              <el-col :span="16"><p style="color: #959494">{{ row.expressNo }}</p></el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8" style="text-align: right"><p style="font-weight: bolder">查询链接</p></el-col>
              <el-col :span="16"><p style="color: #959494">{{ row.expressUrl }}</p></el-col>
            </el-row>
            <el-button slot="reference" size="mini">查看</el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="运费" align="center" prop="pricePay" sortable="custom" width="125px">
        <template slot-scope="{row}">
          <span v-if="row.priceDelivery">￥{{ roundPrice(row.priceDelivery) }}</span>
          <span v-else>暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="支付价格" align="center" prop="pricePay" sortable="custom" width="125px">
        <template slot-scope="{row}">
          <span>￥{{ roundPrice(row.pricePay) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单进度" align="center" prop="orderProgress" sortable="custom" width="120px">
        <template slot-scope="{row}">
          <el-tag v-if="row.orderProgress==0" type="danger" size="mini" effect="dark">{{ progressMap[row.orderProgress] }}</el-tag>
          <el-tag v-else-if="row.orderProgress==1" type="warning" size="mini" effect="dark">{{ progressMap[row.orderProgress] }}</el-tag>
          <el-tag v-else-if="row.orderProgress==2" type="primary" size="mini" effect="dark">{{ progressMap[row.orderProgress] }}</el-tag>
          <el-tag v-else-if="row.orderProgress==3" type="success" size="mini" effect="dark">{{ progressMap[row.orderProgress] }}</el-tag>
          <el-tag v-else type="info" size="mini" effect="dark">{{ progressMap[row.orderProgress] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" prop="createTime" sortable="custom" width="150px">
        <template slot-scope="{row}">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付时间" align="center" prop="payDate" sortable="custom" width="150px">
        <template slot-scope="{row}">
          <span v-if="row.payDate">{{ row.payDate }}</span>
          <span v-else>暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="250px" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleProgress(row)">
            进度
          </el-button>
          <el-button type="primary" size="mini" @click="handleExpress(row)">
            物流
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row.orderId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="batch-operate-container">
      <el-select v-model="operateType" size="small" placeholder="选择批量操作">
        <el-option v-for="item in operates" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button style="margin-left: 10px" type="primary" size="small" @click="handleBatchOperate()">
        确定
      </el-button>
    </div>
    <pagination v-show="total>0" :total="total" :page-num.sync="listQuery.pageNum" :page-size.sync="listQuery.pageSize" @pagination="showSpecialOrderList" />

    <el-dialog title="设置订单进度" :visible.sync="dialogProgressVisible" width="30%">
      <el-form ref="progressForm" :rules="progressRules" :model="tempProgress" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="订单进度" prop="orderProgress">
          <el-select v-model="tempProgress.orderProgress" placeholder="请选择订单进度" class="filter-item">
            <el-option v-for="item in progressList" :key="item.key" :label="item.label" :value="item.key" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogProgressVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="changeProgress()">
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="设置物流信息" :visible.sync="dialogExpressVisible" width="30%">
      <el-form ref="expressForm" :rules="expressRules" :model="tempExpress" label-width="80px" style="width: 400px; margin-left:50px;">
        <el-form-item label="物流单号" prop="expressNo">
          <el-input v-model="tempExpress.expressNo" placeholder="请填写物流单号" />
        </el-form-item>
        <el-form-item label="查询链接" prop="expressUrl">
          <el-input v-model="tempExpress.expressUrl" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请填写查询链接或物流公司名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogExpressVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="changeExpress()">
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择订单商品" :visible.sync="dialogProductVisible" :close-on-press-escape="false" width="1200px" top="50px" @close="handleCloseProductChoose">
      <div class="filter-container">
        <el-input v-model="productListQuery.productName" size="small" placeholder="商品名称" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleProductFilter" />
        <el-button v-waves class="filter-item" size="small" type="primary" icon="el-icon-search" @click="handleProductFilter">
          筛选
        </el-button>
        <span style="margin-left: 20px">* 请单击要选择的商品记录，并点击【确认】</span>
      </div>
      <el-table
        key="productList"
        ref="productTable"
        v-loading="productListLoading"
        :data="productList"
        border
        fit
        max-height="600"
        :cell-style="{'padding-top':'8px', 'padding-bottom':'8px'}"
        highlight-current-row
        style="width: 100%;"
        :row-style="{height:'32px'}"
        :default-sort="{prop: 'productId', order: null}"
        tooltip-effect="light"
        @current-change="handleProductCurrentChange"
        @sort-change="sortProductChange"
      >
        <el-table-column label="编号" align="center" width="100" prop="productId" sortable="custom" fixed>
          <template slot-scope="{row}">
            <span>{{ row.productId }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" min-width="120px" max-width="200px" align="center" show-overflow-tooltip>
          <template slot-scope="{row}">
            <span>{{ row.productName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品图片" width="140px" align="center">
          <template slot-scope="{row}">
            <el-image v-for="(imgUrl, index) in row.productImgList.slice(0,3)" :key="index" style="max-width: 32px; max-height: 24px" :src="imgUrl" fit="contain" :preview-src-list="row.productImgList" />
            <span v-if="row.productImgList.length>3">...</span>
          </template>
        </el-table-column>
        <el-table-column label="简介" min-width="150px" max-width="300px" align="center" show-overflow-tooltip>
          <template slot-scope="{row}">
            <span>{{ row.productDesc }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单价" width="120px" align="center" prop="originPrice" sortable="custom">
          <template slot-scope="{row}">
            <span>￥{{ roundPrice(row.originPrice) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="销量" width="120px" align="center" prop="sales" sortable="custom">
          <template slot-scope="{row}">
            <span>{{ row.sales }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120px" align="center" prop="upper" sortable="custom">
          <template slot-scope="{row}">
            <el-tag v-if="row.upper===1" type="success" size="mini">上架中</el-tag>
            <el-tag v-else type="info" size="mini">已下架</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="productTotal>0" :total="productTotal" :page-num.sync="productListQuery.pageNum" :page-size.sync="productListQuery.pageSize" @pagination="showProductList" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelChooseProduct">
          取消选中
        </el-button>
        <el-button type="primary" @click="handleProductChange">
          确认
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  deleteBasicOrder,
  showSpecialOrderList,
  updateBasicOrderExpress,
  updateBasicOrderProgress,
  batchExportChosenSpecial
} from '@/api/orders'
import { roundPrice } from '@/utils/common'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'
import { showProductList2 } from '@/api/product'

export default {
  name: 'SpecialOrders',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      productLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        orderNumber: '',
        orderProgress: '',
        productId: '',
        departmentId: ''
      },
      progressList: [
        { key: 0, label: '未支付' },
        { key: 1, label: '待发货' },
        { key: 2, label: '待收货' },
        { key: 3, label: '已收货' },
        { key: 4, label: '已关闭' }
      ],
      progressMap: {
        0: '未支付',
        1: '待发货',
        2: '待收货',
        3: '已收货',
        4: '已关闭'
      },
      tempProgress: {
        orderId: undefined,
        orderProgress: undefined
      },
      tempExpress: {
        orderId: undefined,
        expressNo: '',
        expressUrl: ''
      },
      currentProductRow: null,
      tempOrderProduct: '',
      productList: [],
      productTotal: 0,
      productListLoading: true,
      productListQuery: {
        pageNum: 1,
        pageSize: 20,
        mallId: '',
        productName: ''
      },
      dialogProductVisible: false,
      dialogProgressVisible: false,
      dialogExpressVisible: false,
      progressRules: {
        orderProgress: [{ required: true, message: '请选择订单进度', trigger: 'change' }]
      },
      expressRules: {
        expressNo: [{ required: true, message: '请填写快递单号', trigger: 'blur' }]
      },
      operates: [
        { label: '导出选中订单', value: 'batchExportChosen' }
      ],
      operateType: null,
      multipleSelection: []
    }
  },
  created() {
    this.showSpecialOrderList()
  },
  methods: {
    showSpecialOrderList() {
      this.listQuery.departmentId = this.$store.getters.tmpDepartmentId
      this.listLoading = true
      showSpecialOrderList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.showSpecialOrderList()
    },
    sortChange(data) {
      const { prop, order } = data
      this.listQuery.sortProp = prop
      if (order === 'ascending') {
        this.listQuery.sortOrder = '1'
      } else {
        this.listQuery.sortOrder = '-1'
      }
      this.handleFilter()
    },
    resetProgressDialog() {
      this.tempProgress = {
        orderId: undefined,
        orderProgress: undefined
      }
    },
    resetExpressDialog() {
      this.tempExpress = {
        orderId: undefined,
        expressNo: '',
        expressUrl: ''
      }
    },
    handleProgress(row) {
      this.resetProgressDialog()
      this.tempProgress.orderId = row.orderId
      this.tempProgress.orderProgress = parseInt(row.orderProgress)
      this.dialogProgressVisible = true
      this.$nextTick(() => {
        this.$refs['progressForm'].clearValidate()
      })
    },
    changeProgress() {
      this.$refs['progressForm'].validate((valid) => {
        if (valid) {
          updateBasicOrderProgress(this.tempProgress).then(() => {
            this.showSpecialOrderList()
            this.dialogProgressVisible = false
            this.$notify({
              title: 'Success',
              message: '设置进度成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleExpress(row) {
      this.resetExpressDialog()
      this.tempExpress.orderId = row.orderId
      this.tempExpress.expressNo = row.expressNo
      this.tempExpress.expressUrl = row.expressUrl
      this.dialogExpressVisible = true
      this.$nextTick(() => {
        this.$refs['expressForm'].clearValidate()
      })
    },
    changeExpress() {
      this.$refs['expressForm'].validate((valid) => {
        const data = Object.assign({}, this.tempExpress)
        if (valid) {
          updateBasicOrderExpress(data).then(() => {
            this.showSpecialOrderList()
            this.dialogExpressVisible = false
            this.$notify({
              title: 'Success',
              message: '设置物流信息成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(orderId) {
      this.$confirm('此删除操作不可逆, 可能对相关用户产生影响，是否继续?', '提示', {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteBasicOrder(orderId).then(() => {
          this.showSpecialOrderList()
          this.$store.commit('alert/SET_TRUE')
          this.dialogProgressVisible = false
          this.$notify({
            title: 'Success',
            message: '删除订单成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    showProductList() {
      this.productListLoading = true
      showProductList2(this.productListQuery).then(response => {
        this.productList = response.data.list
        this.productTotal = response.data.total
        this.productListLoading = false
      })
    },
    handleProductFilter() {
      this.productListQuery.page = 1
      this.showProductList()
    },
    sortProductChange(data) {
      const { prop, order } = data
      this.productListQuery.sortProp = prop
      if (order === 'ascending') {
        this.productListQuery.sortOrder = '1'
      } else {
        this.productListQuery.sortOrder = '-1'
      }
      this.handleProductFilter()
    },
    handleProductChoose() {
      this.dialogProductVisible = true
      this.showProductList()
    },
    handleCloseProductChoose() {
      this.$refs.productTable.setCurrentRow()
      this.currentProductRow = null
      this.dialogProductVisible = false
    },
    cancelChooseProduct() {
      this.listQuery.productId = ''
      this.tempOrderProduct = ''
      this.handleCloseProductChoose()
    },
    handleProductCurrentChange(val) {
      this.currentProductRow = val
    },
    handleProductChange() {
      if (this.currentProductRow) {
        this.listQuery.productId = this.currentProductRow.productId
        this.tempOrderProduct = `#${this.currentProductRow.productId} ${this.currentProductRow.productName}`
      }
      this.handleCloseProductChoose()
    },
    roundPrice,
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleBatchOperate() {
      if (this.operateType == null) {
        this.$message({ message: '请选择操作类型', type: 'warning' })
        return
      }
      if (this.multipleSelection == null || this.multipleSelection.length < 1) {
        this.$message({ message: '请至少勾选一条数据', type: 'warning' })
        return
      }
      this.$confirm('确认是否进行该批量操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = []
        for (let i = 0; i < this.multipleSelection.length; i++) {
          ids.push(this.multipleSelection[i].orderId)
        }
        switch (this.operateType) {
          case this.operates[0].value:
            this.batchExportChosen(ids)
            break
          default:
            break
        }
      })
    },
    batchExportChosen(ids) {
      const params = new URLSearchParams()
      params.append('ids', ids)
      const loading = this.$loading({
        lock: true,
        text: '正在导出中，请耐心等待',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      batchExportChosenSpecial(params).then((response) => {
        this.$notify({
          title: '选中订单导出成功',
          dangerouslyUseHTMLString: true,
          message: '<p>已导出当前选中的订单，请下载：</p>' +
            '<a target="_blank" href="' + response.data + '">' +
            '<strong style="text-decoration: underline">点击下载</strong>' +
            '</a>',
          type: 'success',
          duration: 0
        })
        loading.close()
      })
    }
  }
}
</script>

<style scoped>
  .info-title{
    font-weight: bolder;
  }
  .info-content{
    font-weight: normal;
  }
  .product-choose-input {
    width: 300px;
    vertical-align: middle;
    margin-bottom: 10px;
  }
</style>
